<template>
	<view class="apply-page">
		<!-- 表单内容 -->
		<view class="form-content">
			<!-- 报修房屋 -->
			<view class="form-item">
				<text class="label">报修房屋</text>
				<input class="input" type="text" v-model="address" placeholder="请输入报修房屋地址" />
			</view>

			<!-- 维修项目 -->
			<view class="form-item">
				<text class="label">维修项目</text>
				<picker @change="onProjectChange" :value="projectIndex" :range="projectNames">
					<view class="value-box">
						<text class="value">{{ project || '请选择维修项目' }}</text>
					</view>
				</picker>
			</view>

			<!-- 标题 -->
			<view class="form-item">
				<text class="label">标题</text>
				<input class="input" type="text" v-model="title" placeholder="请输入" />
			</view>

			<!-- 问题描述 -->
			<view class="form-item">
				<text class="label">问题描述</text>
				<textarea class="textarea" v-model="description" placeholder="请输入" />
			</view>

			<!-- 手机号码 -->
			<view class="form-item">
				<text class="label">手机号码</text>
				<input class="input" type="number" v-model="phone" placeholder="请输入手机号码" />
			</view>

			<!-- 预约日期 -->
			<view class="form-item">
				<text class="label">预约日期</text>
				<picker mode="date" :value="appointmentDate" :start="startDate" :end="endDate" @change="onDateChange">
					<view class="value-box">
						<text class="value">{{ appointmentDate || '请选择预约上门时间' }}</text>
					</view>
				</picker>
			</view>

			<!-- 问题附件 -->
			<view class="form-item">
				<text class="label">问题附件</text>
				<view class="upload-box">
					<view class="image-wrap" v-if="imageUrl">
						<image :src="imageUrl" mode="aspectFill"></image>
						<text class="delete-btn" @click="deleteImage">×</text>
					</view>
					<view class="upload-btn" @click="uploadImage" v-if="!imageUrl">
						<text class="plus">+</text>
						<text class="upload-text">上传(选填)</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 提交按钮 -->
		<view class="submit-btn">
			<button type="primary" @click="submitForm">提交审核</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			const now = new Date()
			const year = now.getFullYear()
			const month = String(now.getMonth() + 1).padStart(2, '0')
			const day = String(now.getDate()).padStart(2, '0')

			return {
				id: '',
				address: '',
				project: '',
				title: '',
				description: '',
				phone: '',
				appointmentDate: '',
				attachments: [],
				projectList: [],
				imageUrl: '',
				maxImages: 4,
				startDate: `${year}-${month}-${day}`,
				endDate: `${year + 1}-${month}-${day}`,
				projectIndex: 0,
				projectNames: [],
				isEdit: false,
				repairId: '',
			}
		},
		// 在组件创建时获取项目列表
		onLoad(options) {
			// 获取项目列表
			this.getProjectList().then(() => {
				// 处理修改时传入的参数
				if (options.repairInfo) {
					this.isEdit = true;
					try {
						const repairInfo = JSON.parse(decodeURIComponent(options.repairInfo));
						this.repairId = repairInfo.id;

						// 更新表单数据
						this.id = repairInfo.id || '';
						this.address = repairInfo.address || '';
						this.project = repairInfo.project || '';
						this.title = repairInfo.title || '';
						this.description = repairInfo.description || '';
						this.phone = repairInfo.phone || '';
						this.appointmentDate = repairInfo.appointmentDate || '';

						// 根据project找到对应的projectIndex
						if (this.project && this.projectList.length > 0) {
							const index = this.projectList.findIndex(item =>
								item.repairItems === this.project ||
								item.repairId === this.project
							);
							if (index !== -1) {
								this.projectIndex = index;
								this.project = this.projectList[index].repairItems;
							}
						}
					} catch (error) {
						console.error('解析维修信息失败:', error);
						uni.showToast({
							title: '数据解析失败',
							icon: 'none'
						});
					}
				}
			});
		},
		methods: {
			/**
			 * 获取维修项目列表
			 * 通过API请求获取所有可用的维修项目
			 * @returns {Promise<void>}
			 */
			async getProjectList() {
				try {
					const {
						data: res
					} = await uni.request({
						url: 'http://localhost:8500/repair/queryAllRepair',
						method: 'GET'
					});

					if (res.code === 200) {
						this.projectList = res.data;
						this.projectNames = this.projectList.map(item => item.repairItems);
					} else {
						throw new Error('获取数据失败');
					}
				} catch (error) {
					console.error('获取维修项目列表失败:', error);
					uni.showToast({
						title: '获取维修项目列表失败',
						icon: 'none'
					});
				}
			},

			/**
			 * 处理维修项目选择变更
			 * 当用户在picker中选择新的维修项目时触发
			 * @param {Object} e - 选择事件对象
			 */
			onProjectChange(e) {
				this.projectIndex = e.detail.value;
				this.project = this.projectNames[this.projectIndex];
			},

			/**
			 * 上传图片
			 * 调用系统相册或相机选择单张图片
			 */
			uploadImage() {
				uni.chooseImage({
					count: 1,
					success: (res) => {
						this.imageUrl = res.tempFilePaths[0]
					}
				})
			},

			/**
			 * 删除已上传的图片
			 * 清空当前已选择的图片
			 */
			deleteImage() {
				this.imageUrl = ''
			},

			/**
			 * 表单验证
			 * 检查所有必填字段是否填写正确
			 * @returns {boolean} 验证是否通过
			 */
			validateForm() {
				const validations = [{
						condition: !this.address.trim(),
						message: '请输入报修房屋地址'
					},
					{
						condition: !this.project,
						message: '请选择维修项目'
					},
					{
						condition: !/^1\d{10}$/.test(this.phone),
						message: '请输入正确的手机号码'
					},
					{
						condition: !this.appointmentDate,
						message: '请选择预约日期'
					}
				]

				for (const validation of validations) {
					if (validation.condition) {
						uni.showToast({
							title: validation.message,
							icon: 'none'
						})
						return false
					}
				}
				return true
			},

			/**
			 * 提交表单
			 * 验证表单并将数据提交到服务器
			 * @returns {Promise<void>}
			 */
			async submitForm() {
				// 表单验证
				if (!this.validateForm()) return

				// 获取当前选中项目的ID
				const selectedProject = this.projectList[this.projectIndex]

				try {
					// 显示加载提示
					uni.showLoading({
						title: '提交中...'
					})

					// 构建请求数据对象
					const requestData = {
						id: this.id,
						address: this.address,
						repairId: selectedProject.id,
						title: this.title,
						description: this.description,
						phone: this.phone,
						appointmentDate: this.appointmentDate,
						image: this.imageUrl
					}

					// 如果是编辑模式，添加维修记录ID
					if (this.isEdit) {
						requestData.id = this.repairId;
					}

					// 根据是否为编辑模式选择不同的接口
					const url = this.isEdit ?
						'http://localhost:8500/repair/updateMaintenanceInfo' :
						'http://localhost:8500/repair/addMaintenanceInfo';

					// 发送请求到后端接口
					const response = await uni.request({
						url: url,
						method: 'POST',
						data: requestData
					})

					uni.hideLoading()

					if (response.data.code === 200) {
						uni.showToast({
							title: this.isEdit ? '修改成功' : '提交成功',
							icon: 'success',
							success: () => {
								setTimeout(() => {
									uni.navigateBack({
										delta: 1
									});
								}, 1500)
							}
						})
					} else {
						throw new Error(response.data.msg || (this.isEdit ? '修改失败' : '提交失败'))
					}
				} catch (error) {
					uni.hideLoading()
					uni.showToast({
						title: error.message || '提交失败',
						icon: 'none'
					})
				}
			},

			/**
			 * 处理日期选择变更
			 * 当用户在日期选择器中选择新日期时触发
			 * @param {Object} e - 日期选择事件对象
			 */
			onDateChange(e) {
				this.appointmentDate = e.detail.value
			},
		}
	}
</script>

<style lang="scss">
	.apply-page {
		min-height: 100vh;
		background: #f5f5f5;
		padding: 20rpx;
	}

	.form-content {
		background: #fff;
		border-radius: 12rpx;
		padding: 0 20rpx;
	}

	.form-item {
		padding: 30rpx 0;
		border-bottom: 1rpx solid #eee;
		display: flex;
		align-items: flex-start;

		.label {
			width: 160rpx;
			font-size: 28rpx;
			color: #333;
		}

		.value-box {
			flex: 1;
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		.value {
			font-size: 28rpx;
			color: #666;
		}

		.arrow {
			color: #999;
		}

		.input {
			flex: 1;
			font-size: 28rpx;
		}

		.textarea {
			flex: 1;
			height: 160rpx;
			font-size: 28rpx;
		}
	}

	.upload-box {
		flex: 1;
	}

	.image-wrap {
		width: 160rpx;
		height: 160rpx;
		position: relative;

		image {
			width: 100%;
			height: 100%;
			border-radius: 8rpx;
		}

		.delete-btn {
			position: absolute;
			top: -10rpx;
			right: -10rpx;
			width: 40rpx;
			height: 40rpx;
			line-height: 40rpx;
			text-align: center;
			background: rgba(0, 0, 0, 0.5);
			color: #fff;
			border-radius: 50%;
		}
	}

	.upload-btn {
		width: 160rpx;
		height: 160rpx;
		background: #f8f8f8;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		border-radius: 8rpx;

		.plus {
			font-size: 40rpx;
			color: #999;
			margin-bottom: 10rpx;
		}

		.upload-text {
			font-size: 24rpx;
			color: #999;
		}
	}

	.submit-btn {
		margin-top: 40rpx;
		padding: 0 20rpx;

		button {
			width: 100%;
			height: 88rpx;
			line-height: 88rpx;
			border-radius: 44rpx;
			font-size: 32rpx;
		}
	}
</style>